import 'package:flutter/material.dart';
import 'package:shining_red_star/api/list_color.dart';
import 'package:shining_red_star/api/list_color_group.dart';
import 'package:shining_red_star/definitions/router.dart';
import 'package:shining_red_star/model/color.dart';
import '../../model/router_params.dart';
import '../../widgets/auto_grid.dart';
import '../../widgets/color_index_card.dart';
import '../../wrappers/safe-area.dart';

class ColorIndexPage extends StatefulWidget {
  const ColorIndexPage({super.key});

  @override
  State<ColorIndexPage> createState() => _ColorIndexPageState();
}

class _ColorIndexPageState extends State<ColorIndexPage> {
  List<ColorInfo> colorList = [];

  void loadData() {
    Future.wait([listColorGroup(), listColor()]).then((res) {
      List<ColorGroup> colorGroupList = res[0] as List<ColorGroup>;
      List<ColorInfo> colorInfoList = res[1] as List<ColorInfo>;
      setState(() {
        colorList = colorGroupList
            .map<FixedColorGroup>((group) => FixedColorGroup(
                id: group.id,
                title: group.title,
                colorList: colorInfoList
                    .where((color) => color.group.contains(group.id))
                    .toList()))
            .firstWhere((group) => group.id == 'common')
            .colorList;
      });
    });
  }

  void nav({String? group, String? id}) {
    Navigator.pushNamed(context, RouterKey.colorDetail.value,
        arguments: CommonDetailRouterArguments(
          id: id,
          group: group,
        ));
  }

  @override
  void initState() {
    super.initState();
    loadData();
  }

  @override
  Widget build(BuildContext context) {
    int i = 0;
    return SafeAreaPageWrapper(
      padding: EdgeInsets.all(12),
      child: colorList.isEmpty
          ? Center(
              child: Text('数据加载中'),
            )
          : AutoGrid(
              expectItemWidth: 96,
              expectItemHeight: 118,
              mainAxisSpacing: 12,
              crossAxisSpacing: 12,
              calcHeight: (itemWidth) {
                return itemWidth + 30;
              },
              children: colorList.map((item) {
                return ColorIndexCard(
                  autofocus: i++ == 0,
                  color: item,
                  onConfirm: () {
                    nav(group: 'common', id: item.value);
                  },
                );
              }).toList(),
            ),
    );
  }
}
